package org.net5ijy.security.config.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.net5ijy.security.config.security.SecurityConfig;
import org.net5ijy.security.util.RequestUtil;
import org.net5ijy.security.util.exception.ValidateCodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/**
 * CustomAuthenticationFailureHandler
 *
 * @author XGF
 * @date 2020/11/30 22:31
 */
@Component
public class CustomAuthenticationFailureHandler extends
    SimpleUrlAuthenticationFailureHandler {

  private static Logger log = LoggerFactory
      .getLogger(CustomAuthenticationFailureHandler.class);

  public static final String SESSION_LOGIN_EXCEPTION_KEY = "loginException";

  @Override
  public void onAuthenticationFailure(HttpServletRequest request,
      HttpServletResponse response, AuthenticationException exception)
      throws IOException, ServletException {

    log.error(exception.getMessage(), exception);

    if (exception.getClass().equals(ValidateCodeException.class)) {
      request.getSession().setAttribute(SESSION_LOGIN_EXCEPTION_KEY, exception);
    }

    // 获取登录失败页url
    String url = RequestUtil.getRedirectUrl(request, SecurityConfig.LOGIN_ERROR_URL);
    response.sendRedirect(url);
  }
}
